from typing import Tuple, Union, List, Optional, Callable, Any
from fastapi import FastAPI
from afast_core.core_libs.cache_house.backends import RedisFactory
from afast_core.core_libs.cache_house.helpers import pickle_encoder, pickle_decoder, DEFAULT_NAMESPACE, DEFAULT_PREFIX, \
    key_builder
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings


class CacheHousePluginClient(BasePlugin):
    # 设置插件默认的参数信息
    name = 'CacheHouse'

    class CacheSettings(Settings):
        password: str = None
        db: int = 0
        host: str = "localhost"
        port: int = 6379
        encoder: Callable[..., Any] = pickle_encoder
        decoder: Callable[..., Any] = pickle_decoder
        namespace: str = DEFAULT_NAMESPACE
        key_prefix: str = DEFAULT_PREFIX
        key_builder: Callable[..., Any] = key_builder
        cluster_mode: bool = False

    def setup(self, app: FastAPI, name: str = None, *args, **redis_kwargs):
        """插件初始化"""
        self.app = app
        print('self.settings.password',self.settings.password)
        @app.on_event("startup")
        async def startup():
            self._cache = RedisFactory.init(host=self.settings.host,
                                            port=self.settings.port,
                                            password=self.settings.password,
                                            db=self.settings.db,
                                            cluster_mode=self.settings.cluster_mode,
                                            encoder=self.settings.encoder,
                                            decoder=self.settings.decoder,
                                            namespace=self.settings.namespace,
                                            key_prefix=self.settings.key_prefix,
                                            key_builder=self.settings.key_builder,
                                            **redis_kwargs
                                            )
            # 返回的是：RedisCache里面对象实例
            app.cache_house = self._cache

        @app.on_event("shutdown")
        async def shutdown():
            RedisFactory.close_connections()
